package br.com.fiap.fiappizzas.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.fiap.fiappizzas.db.entities.Order;
import br.com.fiap.fiappizzas.db.entities.OrderProduct;
import br.com.fiap.fiappizzas.db.entities.Product;

public class OrderProductDAO extends AbstractDAO<OrderProduct> {
	
	private ProductDAO productDAO;
	
	public OrderProductDAO(Context context) {
		super(context);
		productDAO = new ProductDAO(context);
	}

	@Override
	public String getTableName() {
		return "tb_order_product";
	}

	@Override
	public String[] getColumns() {
		return new String[]{"id", "order", "product"};
	}

	@Override
	public OrderProduct buildEntity(Cursor cursor) {
		
		final OrderProduct op = new OrderProduct();
		
		op.setId(cursor.getLong(0));
		op.setOrderId(cursor.getLong(1));
		op.setProductId(cursor.getLong(2));
		
		return op;
	}

	@Override
	public ContentValues buildContentValues(OrderProduct entity) {
		
		final ContentValues values = new ContentValues();
        
		values.put("id", entity.getId());  
        values.put("order", entity.getOrderId());
        values.put("product", entity.getProductId());
        
        return values;
		
	}
	
	public void delete(Long orderId, Long productId) {

		final SQLiteDatabase db = getWritableDB();
 
        db.delete(getTableName(), //table name
                "order = ? AND product = ?",  // selections
                new String[] { String.valueOf(orderId), String.valueOf(productId) }); //selections args
 
        db.close();
 
	}
	
	public List<Product> findProductsByOrder(Order order) {
		
		final SQLiteDatabase db = getReadableDB();
		
		Cursor cursor = 
	            db.query(getTableName(), // a. table
	            getColumns(), // b. column names
	            "order = ?", // c. selections 
	            new String[]{String.valueOf(order.getId())}, // d. selections args
	            null, // e. group by
	            null, // f. having
	            null, // g. order by
	            null); // h. limit
		
		if (cursor != null) cursor.moveToFirst();
		
		final List<Product> products = new ArrayList<Product>(cursor.getCount());
		
		while (cursor.moveToNext()) {
			final OrderProduct orderProduct = buildEntity(cursor);
			
			final Product p = productDAO.getEntityById(orderProduct.getProductId());
			
			products.add(p);
		}
		
		return products;
		
	}

}
